<template>
  <swiper
    :style="{ height: swiperHeight + 'px', transition: 'height 0.3s ease' }"
    @change="onSwiperChange"
    :previous-margin="previousMargin"
    :next-margin="nextMargin"
    :circular="circular"
    :indicator-dots="indicatorDots"
    :autoplay="autoplay"
    class="auto-height-swiper"
  >
    <swiper-item
      v-for="(item, index) in items"
      :key="index"
    >
      <view
        :id="getSlideId(index)"
        class="swiper-item-content"
      >
        <slot :item="item" :index="index">{{ item }}</slot>
      </view>
    </swiper-item>
  </swiper>
</template>

<script>
export default {
  name: 'AutoHeightSwiper',
  props: {
    items: {
      type: Array,
      required: true
    },
    previousMargin: {
      type: String,
      default: '0rpx'
    },
    nextMargin: {
      type: String,
      default: '0rpx'
    },
    circular: {
      type: Boolean,
      default: false
    },
    indicatorDots: {
      type: Boolean,
      default: true
    },
    autoplay: {
      type: Boolean,
      default: false
    },
    minHeight: {
      type: Number,
      default: 300
    }
  },
  data() {
    return {
      swiperHeight: this.minHeight,
      currentIndex: 0
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.updateSwiperHeight(this.currentIndex)
    })
  },
  methods: {
    getSlideId(index) {
      return `slide-${index}`
    },
    onSwiperChange(e) {
      this.currentIndex = e.detail.current
      this.updateSwiperHeight(this.currentIndex)
    },
    updateSwiperHeight(index) {
      const id = `#${this.getSlideId(index)}`
      this.$nextTick(() => {
        uni.createSelectorQuery()
          .in(this)
          .select(id)
          .boundingClientRect(res => {
            if (res && res.height) {
              this.swiperHeight = Math.max(res.height, this.minHeight)
            }
          })
          .exec()
      })
    },
    // 新增 refreshHeight，供外部调用
    refreshHeight() {
      // 延迟执行，等动画和 DOM 完成
      setTimeout(() => {
        this.updateSwiperHeight(this.currentIndex)
      }, 0)  // 延时可调
    }
  }
}
</script>

<style scoped>
.auto-height-swiper {
  width: 100%;
}
.swiper-item-content {
  /* 自定义样式 */
  padding: 20rpx;
  box-sizing: border-box;
}
</style>
